package blue.txt.handle;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.blue.core.util.NumberUtil;

import blue.txt.model.FileModel;

/**
 * 章节解析器
 * 
 * @author zhengj
 * @since 1.0 2017年7月4日
 */
public class ChapterContentParser implements ContentParser
{
	private static final Pattern[] INTRODUCTIONS = { Pattern.compile("(序)章") };
	private static final Pattern[] CHAPTERS = { Pattern.compile("第([一二三四五六七八九十零百千万0-9]+)章[\\s、　\\.]+(.+)") };

	public ChapterContentParser()
	{
	}

	@Override
	public FileModel parse(String line, FileModel model, AtomicInteger atomic)
	{
		if (model == null)
			model = new FileModel();

		if (this.parseIntroduction(line, model))
		{
			model.setIndex(atomic.getAndIncrement());
			return model;
		}

		if (this.parseChapter(line, model))
		{
			model.setIndex(atomic.getAndIncrement());
			return model;
		}

		return null;
	}

	private boolean parseIntroduction(String line, FileModel model)
	{
		for (Pattern pattern : INTRODUCTIONS)
		{
			Matcher matcher = pattern.matcher(line);
			if (matcher.find())
			{
				model.setChapter(0);
				model.setTitle("序章");
				return true;
			}
		}
		return false;
	}

	private boolean parseChapter(String line, FileModel model)
	{
		for (Pattern pattern : CHAPTERS)
		{
			Matcher matcher = pattern.matcher(line);
			if (matcher.find())
			{
				String chapter = matcher.group(1);
				String title = matcher.group(2);

				model.setChapter(NumberUtil.chnToInt(chapter));
				model.setTitle(title);
				//System.out.println("原始：" + line);
				return true;
			}
		}
		return false;
	}

}
